import { routerRedux } from 'dva/router';
import { stringify } from 'qs';
import { message } from 'antd';
import { fakeAccountLogin, accountLogin, getFakeCaptcha, logout } from '@/services/api';
import { setAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
import { reloadAuthorized } from '@/utils/Authorized';
import { patchRoutes } from '@/utils/authRoutes';

export default {
  namespace: 'login',

  state: {
    status: undefined,
  },

  effects: {
    *login({ payload }, { call, put }) {
      const response = yield call(accountLogin, payload);
      if (typeof response === 'undefined') {
        return;
      }
      if (response.status === 'ok') {
        window.currentName = payload.userName;
        window.reloadFlag = 1;
        if (payload.userName !== 'superadmin') {
          /* let authRoutes ={
             '/form': { authority: [ 'user'] },
           }; */
          const authRoutes = {};
          for (let i = 0; i < response.permissionList.length; i++) {
            const { url } = response.permissionList[i];
            authRoutes[url] = { authority: [payload.userName] };
          }
          patchRoutes(authRoutes);
          response.currentAuthority = payload.userName;
        } else {
          response.currentAuthority = 'admin';
        }
      }
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });
      // Login successfully
      if (response.status === 'ok') {
        reloadAuthorized();
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let { redirect } = params;
        if (redirect) {
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);
            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            redirect = null;
          }
        }
        // debugger
        yield put(routerRedux.replace(redirect || '/'));
      }
    },

    *getCaptcha({ payload }, { call }) {
      yield call(getFakeCaptcha, payload);
      if (typeof response === 'undefined') {
      }
    },

    *logout(_, { call, put }) {
      const response = yield call(logout);
      if (response.code === 1) {
        window.currentName = '';
        yield put({
          type: 'changeLoginStatus',
          payload: {
            status: false,
            currentAuthority: 'guest',
          },
        });
        reloadAuthorized();
        // redirect
        if (window.location.pathname !== '/user/login') {
          yield put(
            routerRedux.replace({
              pathname: '/user/login',
              search: stringify({
                redirect: window.location.href,
              }),
            })
          );
        }
      } else {
        message.error(response.message);
      }
    },

    *relogout(_, { call, put }) {
      const response = yield call(logout);
      if (response.code === 1) {
        yield put({
          type: 'changeLoginStatus',
          payload: {
            status: false,
            currentAuthority: 'guest',
          },
        });
        reloadAuthorized();
      }
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      setAuthority(payload.currentAuthority);
      return {
        ...state,
        status: payload.status,
        type: payload.type,
        permissionList: payload.permissionList,
      };
    },
  },
};
